package com.nwpu.hass.serviceimpl;

import com.nwpu.hass.domain.DeviceEntity;
import com.nwpu.hass.domain.JsonResponse.RepairApplyResponse;
import com.nwpu.hass.domain.RegisterformEntity;
import com.nwpu.hass.domain.UserEntity;
import com.nwpu.hass.domain.WarrantyEntity;
import com.nwpu.hass.repository.DeviceRepository;
import com.nwpu.hass.repository.RegisterformRepository;
import com.nwpu.hass.repository.UserRepository;
import com.nwpu.hass.repository.WarrantyRepository;
import com.nwpu.hass.service.MessageService;
import com.nwpu.hass.service.WarrantyService;
import com.nwpu.hass.utils.Code;
import com.nwpu.hass.utils.Status;
import com.nwpu.hass.utils.Tools;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class WarrantyServiceImpl implements WarrantyService {

    @Resource
    private WarrantyRepository warrantyRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private DeviceRepository deviceRepository;
    @Resource
    private RegisterformRepository registerformRepository;
    @Resource
    private MessageService messageService;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String appendRepair(long deviceId, String reason, long userId) {
        DeviceEntity deviceEntity = deviceRepository.findDeviceEntityByDeviceId(deviceId);
        if(Objects.isNull(deviceEntity)){
            return "设备不存在";
        }
        if(deviceEntity.getStatus()!= Status.BUSY.getStatus()){
            return "当前设备不处于使用状态";
        }
        Long borrowPerson = registerformRepository.findByDeviceId(deviceId).get(0).getBorrowPerson();
        if(borrowPerson!=userId){
            return "不能报修他人正在使用的设备" ;
        }
        deviceEntity.setStatus(Status.ONREPAIR.getStatus());
        deviceRepository.save(deviceEntity);
        WarrantyEntity warrantyEntity = new WarrantyEntity();
        warrantyEntity.setApplyTime(Tools.timestamp());
        warrantyEntity.setDevice(deviceId);
        warrantyEntity.setReason(reason);
        warrantyEntity.setApplyPerson(userId);
        warrantyEntity.setRecord(Tools.timestamp());
        warrantyRepository.save(warrantyEntity);

        messageService.addSystemMessage("有人报修了" + deviceEntity.getFamily() + deviceEntity.getType() +
                "，快来处理吧~~~");
        return "OK";
    }

    @Override
    public RepairApplyResponse getOneRepairRecord(long recordId) {

        Optional<WarrantyEntity> warrantyEntityOptional = warrantyRepository.findById(recordId);
        if(warrantyEntityOptional.isPresent()) {
            WarrantyEntity warrantyEntity = warrantyEntityOptional.get();
            long userId = warrantyEntity.getApplyPerson();
            long deviceId = warrantyEntity.getDevice();
            Optional<UserEntity> ueOptional = userRepository.findById(userId);
            Optional<DeviceEntity> deOptional = deviceRepository.findById(deviceId);
            if(ueOptional.isPresent() && deOptional.isPresent()) {
                UserEntity userEntity = ueOptional.get();
                DeviceEntity deviceEntity = deOptional.get();
                return new RepairApplyResponse(userEntity,
                        warrantyEntity.getApplyTime(), deviceEntity,warrantyEntity.getWarrantyId(),
                        warrantyEntity.getReason());
            }
        }
        return null;
    }

    /**
     * @param id 记录id
     * @param status 是否通过
     */
    @Override
    public String checkOneById(Long id, boolean status) {
        Optional<WarrantyEntity> warrantyEntityOptional = warrantyRepository.findById(id);
        if(warrantyEntityOptional.isPresent()) {
            WarrantyEntity warrantyEntity = warrantyEntityOptional.get();
            Optional<DeviceEntity> deviceEntityOptional = deviceRepository.findById(warrantyEntity.getDevice());
            if(deviceEntityOptional.isPresent()) {
                DeviceEntity deviceEntity = deviceEntityOptional.get();
                if(deviceEntity.getStatus()!=-3){
                    return "设备不处于申请报修状态";
                }
                deviceEntity.passOrNot(status);
                deviceRepository.save(deviceEntity);

                String msgContent;
                if(status) {
                    msgContent = "管理员接受了您在" + sdf.format(warrantyEntity.getApplyTime()) + "对" +
                            deviceEntity.getFamily() +deviceEntity.getType() + "的报修请求:)";
                } else {
                    msgContent = "管理员拒绝了您在" + sdf.format(warrantyEntity.getApplyTime()) + "对" +
                            deviceEntity.getFamily() +deviceEntity.getType() + "的报修请求:(";
                }
                messageService.addMessage(warrantyEntity.getApplyPerson(), msgContent);
                return "OK";
            }
        }
        return "recordId不存在";
    }

    @Override
    public List<RepairApplyResponse> getCheckList(int pageNo) {
        List<RepairApplyResponse> responses = new ArrayList<>();
        // 处于报修申请状态的设备
        List<DeviceEntity> deviceEntities = deviceRepository.findRepairing(pageNo*7-7,7);
        if(!deviceEntities.isEmpty()){
            for(DeviceEntity deviceEntity:deviceEntities){
                // 记录中可能有多条关于这个设备的保修记录，因此需要找时间最晚的
                WarrantyEntity warrantyEntity = warrantyRepository.findAllByDeviceOrderByRecordDesc(deviceEntity.getDeviceId()).get(0);
                UserEntity userEntity = userRepository.findUserEntityByUserid(warrantyEntity.getApplyPerson());
                RepairApplyResponse response = new RepairApplyResponse(userEntity,warrantyEntity.getApplyTime(),deviceEntity,warrantyEntity.getWarrantyId(),warrantyEntity.getReason());
                responses.add(response);
            }
        }
        return responses;
    }
}
